<template>
  <el-drawer v-model="drawer" title="课程编辑"
    size="800"
    @closed="handleClose"
  >
    <ContentBody v-loading="store.updating">
      <el-form ref="refLessonForm"
        :model="store.lesson"
        :rules="rules"
        label-width="120px"
        style="width:90%"
        v-if="store.lesson"
      >
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="store.lesson.title" placeholder="请填写课程名称" />
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-cascader v-model="store.lesson.categoryId" 
            placeholder="请选择分类" 
            :options="store.categories"
            :props="{
              expandTrigger: 'hover',
              value: 'id',
              label: 'title'
            }"
          />
        </el-form-item>
        <el-form-item label="课程封面" prop="thumb">
          <ImageUpload v-model="store.lesson.thumb" />
        </el-form-item>
        <el-form-item label="课程价格" prop="price">
          <el-input v-model="store.lesson.price" placeholder="请填写课程价格" />
        </el-form-item>
        <el-form-item label="市场价格" prop="marketPrice">
          <el-input v-model="store.lesson.marketPrice" placeholder="请填写市场价格" />
        </el-form-item>
        <el-form-item label="讲课老师" prop="teachers">
          <el-input v-model="store.lesson.teachers" placeholder="请填写讲课老师" />
        </el-form-item>
        <el-form-item label="课程简介" prop="summary">
          <el-input type="textarea" v-model="store.lesson.summary" placeholder="请填写课程简介" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </el-form-item>
      </el-form>
    </ContentBody>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useLessonStore } from '@/stores/lesson'
import { ElMessage } from 'element-plus'
import ImageUpload from '@/components/upload/single.vue'

const drawer = ref(false)
const store = useLessonStore()
const router = useRouter()
const route = useRoute()
const refLessonForm = ref()

const rules = {
  title: [{required: true, message: '未填写标题', trigger: 'blur'}],
  categoryId: [{required: true, message: '未选择分类', trigger: 'blur'}],
  thumb: [{required: true, message: '未选择封面', trigger: 'blur'}],
}

const handleSave = () => {
  refLessonForm.value.validate(async(valid: boolean) => {
    if (valid) {
      const result = await store.saveLesson()
      if (result) {
        ElMessage.success('保存成功')
        store.loadLessons()
        router.back()
      }
    }
  })
}
const handleClose = () => {
  drawer.value = false
  router.back()
}

onMounted(() => {
  drawer.value = true
  if (route.params.id) {
    store.loadLesson(parseInt(route.params.id as string))
  } else {
    store.newLesson()
  }
})
</script>